package com.meibei.ljl.test01;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

import static com.meibei.ljl.test01.R.id.chat_send;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private EditText edit;
    private Button send;
    private MsgAdapter msgAdapter;
    private List<Msg> list;
    private LinearLayoutManager layoutManager;
    private Msg msg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.chat_recyclerview);
        edit = (EditText) findViewById(R.id.chat_edit);
        send = (Button) findViewById(chat_send);
        initMsgs();//初始化消息数据
        msgAdapter = new MsgAdapter(this, list);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(msgAdapter);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = edit.getText().toString();
                if (content != null) {
                    msg = new Msg(content, Msg.TYPE_SEND);
                    list.add(msg);
                    msgAdapter.notifyDataSetChanged();//当有新消息时，刷新recyclerView中的控件
                    recyclerView.smoothScrollToPosition(list.size());//将recyclerView定位到最后一行
                    edit.setText("");//清空输入框中的内容
                }
            }
        });


    }

    private void initMsgs() {
        list = new ArrayList<Msg>();
        Msg msg1 = new Msg("Hello Girl!", Msg.TYPE_RECEIVED);
        list.add(msg1);
        Msg msg2 = new Msg("Hey......", Msg.TYPE_SEND);
        list.add(msg2);
        Msg msg3 = new Msg("What are you doing?", Msg.TYPE_RECEIVED);
        list.add(msg3);
    }
}
